package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket socket=null;

    public Server(int port) throws IOException {
        socket=new ServerSocket(port);
    }

    public void start() throws IOException {
        ExecutorService thread= Executors.newCachedThreadPool();
        System.out.println("Server is Running...");
        while(true){
            Socket clientSocket=socket.accept();
           thread.submit(new Runnable() {
               @Override
               public void run() {
                   try {
                       connection(clientSocket);
                   } catch (IOException e) {
                       throw new RuntimeException(e);
                   }
               }
           });
//            Thread t=new Thread(()->{
//                try {
//                    connection(clientSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            t.start();
        }
    }

    private void connection(Socket clientSocket) throws IOException {
        System.out.printf("Client:%s:%d\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream();
            PrintWriter printWriter=new PrintWriter(outputStream)){
            while(true){
                Scanner scanner=new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.printf("Client:%s:%d is quiting\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                String request=scanner.next();
                String response=process(request);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req:%s res:%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);

            }
        }finally {
            clientSocket.close();
        }
    }

    public String process(String request) {
    return request;
    }

    public static void main(String[] args) throws IOException {
    Server server=new Server(9090);
    server.start();
    }
}
